package com.sgb.kjwl.view.ui.activity.manage

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.sgb.capital.view.widget.MToast
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityAgentStaffCheckAddBinding
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent
import com.sgb.kjwl.di.manage.EnterpriseManageModule
import com.sgb.kjwl.model.entity.manage.AgentStaffCheckEntity
import com.swgk.core.event.EventConstant
import com.sgb.kjwl.view.event.RoleListEntity
import com.sgb.kjwl.view.event.self.AgentApplyEvent
import com.swgk.core.view.CityPickBuilder
import com.swgk.core.view.CityPickView
import com.sgb.kjwl.viewmodel.manage.AgentCheckModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.customview.ItemInputTextView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

//员工审核---添加成员
class AgentStaffCheckAddActivity : AppActivity(), ItemInputTextView.OnWholeItemClickListener {

    private var mEntity : AgentStaffCheckEntity ?= null
    @Inject
    lateinit var mViewModel : AgentCheckModel

    private lateinit var mBinding : ActivityAgentStaffCheckAddBinding

    //二级联动数据
    private var rolesList =  ArrayList<ArrayList<RoleListEntity>>()

    private val firstRoleList = ArrayList<RoleListEntity>()

    // 二级联动数据的第二级数据
    private var opt2 : ArrayList<RoleListEntity> ?= null

    private var rolePosition1 = 0
    private var rolePosition2 = 0

    companion object{
        const val KEY_ENTITY = "key_entity"
        const val REQUEST_CODE_DEPARTMENT = 20013
        fun launch(context: Context, entity: AgentStaffCheckEntity){
            val intent = Intent(context, AgentStaffCheckAddActivity::class.java)
            intent.putExtra(KEY_ENTITY, entity)
            context.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
            .enterpriseManageModule(EnterpriseManageModule()).build().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (intent != null){
            mEntity = intent.getSerializableExtra(AgentStaffCheckDetailActivity.KEY_ENTITY) as AgentStaffCheckEntity?
        }
        if (mEntity == null){
            finish()
            return
        }
        mBinding.tvItvName.content = mEntity!!.name
        mBinding.tvItvPhone.content = mEntity!!.phone
        EventBus.getDefault().register(this)
    }

    override fun initView() {
        super.initView()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_agent_staff_check_add)
        mBinding.include.ivBack.setOnClickListener { finish() }
        mBinding.include.titleView.text = "添加成员"
        mBinding.tvFinish.setOnClickListener {
            //添加完成
            addStaff()
        }
        mBinding.tvItvRole.setOnWholeItemClickListener(this)
        mBinding.tvItvDepartment.setOnWholeItemClickListener(this)
        mViewModel.roleList.observe(this, {
            firstRoleList.clear()
            firstRoleList.addAll(it)
            rolesList.clear()
            for (entity in firstRoleList){
                opt2 = ArrayList()
                opt2!!.addAll(entity.children)
                rolesList.add(opt2!!)
            }
            showRolePop()
        })
        mViewModel.addStaffSuccess.observe(this, {
            MToast.showToast(this, it)
            EventBus.getDefault().post(
                AgentApplyEvent.make(EventConstant.EVENT_AGENT_APPLY_SUCCESS)
            )
            finish()
        })
    }

    private fun addStaff() {
        if (TextUtils.isEmpty(mEntity!!.deptName)){
            mEntity!!.deptName = mEntity!!.sComName
        }
        if (TextUtils.isEmpty(mEntity!!.deptNo)){
            mEntity!!.deptNo = "1"
        }
        mViewModel.addStaff(this, mEntity!!)
        resources
    }

    private fun showRolePop() {
        if (firstRoleList.isEmpty() || rolesList.isEmpty()) return
        val roleOption : CityPickView<RoleListEntity> = CityPickBuilder(this@AgentStaffCheckAddActivity,
                object : OnOptionsSelectListener {
                    override fun onOptionsSelect(
                            options1: Int,
                            options2: Int,
                            options3: Int,
                            v: View?
                    ) {
                        rolePosition1 = options1
                        rolePosition2 = options2
                        if (!TextUtils.isEmpty(rolesList[options1][options2].toString())) {
                            mBinding.tvItvRole.content = firstRoleList[options1].name + "_" + rolesList[options1][options2].name
                            mEntity!!.roleName = rolesList[options1][options2].name
                            mEntity!!.roleNo = rolesList[options1][options2].userNo
                        }
                    }
                }).setCancelText("取消").setSubCalSize(15)
            .setCancelColor(resources.getColor(R.color.color_tab_two))
            .setTitleText("请选择角色")
            .setTitleColor(resources.getColor(R.color.color_tab_three)).setTitleSize(15)
            .setSubmitText("确定")
            .setSubmitColor(resources.getColor(R.color.color_main))
            .build()
        roleOption.setPicker(firstRoleList, rolesList)
        roleOption.setSelectOptions(rolePosition1, rolePosition2)
        roleOption.show()
    }

    override fun OnWholeItemClick(view: View?) {
        when(view!!.id){
            R.id.tv_itv_role -> {
                //角色
                if (rolesList.isNotEmpty()){
                    showRolePop()
                } else {
                    mViewModel.getRoleList(this, mEntity!!.comNo)
                }
            }
            R.id.tv_itv_department -> {
                //部门
                //AgentStaffCheckDepartmentActivity.launch(this, mEntity!!, REQUEST_CODE_DEPARTMENT)
                AgentStaffCheckDepartmentActivity.launch(this, mEntity, REQUEST_CODE_DEPARTMENT)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_DEPARTMENT && resultCode == Activity.RESULT_OK
            && data != null && data.getSerializableExtra(AgentStaffCheckDepartmentActivity.KEY_DATA) != null
            && data.getSerializableExtra(AgentStaffCheckDepartmentActivity.KEY_DATA) is AgentStaffCheckEntity){
             mEntity = data.getSerializableExtra(AgentStaffCheckDepartmentActivity.KEY_DATA) as AgentStaffCheckEntity
             mBinding.tvItvDepartment.content = if (TextUtils.isEmpty(mEntity!!.deptName)) mEntity!!.sComName else mEntity!!.deptName
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(event : AgentApplyEvent){
        if (event.messageTag == EventConstant.EVENT_AGENT_APPLY_CHOOSE_DEPT_SUCCESS){
            if (event.messageData is AgentStaffCheckEntity){
                mEntity = event.messageData as AgentStaffCheckEntity
                mBinding.tvItvDepartment.content = if (TextUtils.isEmpty(mEntity!!.deptName)) mEntity!!.sComName else mEntity!!.deptName
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}